from re import match

import re

from celery_tasks.email.tasks import send_verify_email
from django_redis import get_redis_connection
from rest_framework import serializers

from goods.models import SKU
from users import constants
from users.models import Users, Address
from rest_framework_jwt.settings import api_settings


class CreateUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)

    class Meta:
        model = Users
        fields = ('id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_allow(self,value):
        print('test')
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    def validate_mobile(self,value):
        if not match(r'1[3-9]\d{9}$',value):
            raise serializers.ValidationError("手机号格式不正确")
        return value

    def validate(self,attr):
        # 校验密码
        print(123456789)
        if attr['password'] != attr['password2']:
            raise serializers.ValidationError('两次密码不一致')

        mobile = attr['mobile']
        print(mobile)
        redis_conn = get_redis_connection("verify_codes")
        sms_code_text = redis_conn.get('sms_%s'% mobile)
        print('什么鬼')
        yanzhengma = sms_code_text.decode('utf-8')

        # 校验短信验证码
        if not sms_code_text:
            raise serializers.ValidationError("短信验证码失效")
        if attr['sms_code'] != yanzhengma :

            raise serializers.ValidationError('短信验证码错误')


        return attr

    def create(self,Validated_data):

        del Validated_data["password2"]
        del Validated_data['sms_code']
        del Validated_data['allow']


        user = Users.objects.create(**Validated_data)
        user.set_password(Validated_data['password'])
        user.save()

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user

class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Users
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Users
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    def update(self, instance, validated_data):
        email = validated_data['email']
        instance.email = email
        instance.save()

        # 生成验证链接
        verify_url = instance.generate_verify_email_url()
        # 发送验证邮件
        send_verify_email.delay(email, verify_url)
        return instance

class UserAddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label="省ID",required=True)
    city_id = serializers.IntegerField(label='市ID',required=True)
    district_id = serializers.IntegerField(label='区ID',required=True)
    # is_
    class Meta:
        model = Address
        exclude = ('user','create_time','update_time','is_deleted')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存
        """
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)


class AddUserBrowsingHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='商品SKU编号',min_value=1)

    def validate_sku_id(self,value):

        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return value

    def create(self, validated_data):

        user_id = self.context['request'].user.id
        sku_id = validated_data['sku_id']

        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()
        pl.lrem('history_%s' % user_id,0,sku_id)
        pl.lpush('history_%s' % user_id,sku_id)
        pl.ltrim("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)
        pl.execute()

        return validated_data

class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id','name','price','default_image_url','comments')

